package com.cn.wanxi.service.impl;

import com.cn.wanxi.dao.CompanyDao;
import com.cn.wanxi.dao.impl.CompanyImpl;
import com.cn.wanxi.model.CompanyModel;
import com.cn.wanxi.service.ICompanyService;
import redis.clients.jedis.Jedis;

public class CompanyServiceImpl implements ICompanyService {
    /**
     * 如果有大量客户访问当前页面时，需要进行判断
     * 1.数据来源
     * 2.一般情况下数据域来源于数据库
     * 3.如果有大量客户查询时，第一次查询数据库，后面用户都是查询缓存redis
     * 4.如果缓存里面有数据，则取缓存，否则取数据库
     *
     * @return
     */
    @Override
    public CompanyModel getCompanyModel() {
        Jedis jedis = new Jedis();//得到缓存的对象
        CompanyModel companyModel = new CompanyModel();
//        判断缓存是否有数据
        Boolean boo = jedis.exists("logo");
        if (boo) {
            companyModel.setLogo(jedis.get("logo"));
            companyModel.setPhone(jedis.get("phone"));
            companyModel.setNet(jedis.get("net"));
            companyModel.setEmail(jedis.get("email"));
            companyModel.setLinePhone(jedis.get("linePhone"));
            companyModel.setAddress(jedis.get("address"));
            companyModel.setVersion(jedis.get("version"));

        } else {
//            将数据从数据库里取出，并保存到缓存

            CompanyDao companyDao = new CompanyImpl();
            companyModel = companyDao.getCompanyModel();
//            req.setAttibute("key",companyModel);

            jedis.select(15);
            jedis.set("logo", companyModel.getLogo());
//            jedis.setex("logo", 100, companyModel.getLogo());//原子性
//            jedis.expire("logo", 100);
            jedis.set("phone", companyModel.getPhone());
            jedis.set("net", companyModel.getNet());
            jedis.set("email", companyModel.getEmail());
            jedis.set("linePhone", companyModel.getLinePhone());
            jedis.set("address", companyModel.getAddress());
            jedis.set("version", companyModel.getVersion());

        }
        return companyModel;
    }

    public int update(CompanyModel companyModel) {
        CompanyDao companyDao = new CompanyImpl();
        int result = companyDao.update(companyModel);
        if (result == 1) {
            Jedis jedis = new Jedis();
            jedis.del("logo", "phone", "net");
        }
        return result;
    }

    public int del(CompanyModel companyModel) {
        CompanyDao companyDao = new CompanyImpl();
        int result = companyDao.del(companyModel);
        if (result == 1) {
            Jedis jedis = new Jedis();
            jedis.del("logo");
        }
        return result;
    }
}
